
//
//  MTQuestionAnswerVC.m
//  met
//
//  Created by 李晓俊 on 2019/5/20.
//  Copyright © 2019 李晓俊. All rights reserved.
//

#import "MTQuestionNpcAnswerVC.h"
#import "MTQuestionAnswerView.h"
#import "XJTypeWriterTextView.h"
#import "CLChocieAnswerButton.h"
#import "ChatViewController.h"

#define kChoiceButtonTag  2000
#import "MTFeedBackVC.h"

@interface MTQuestionNpcAnswerVC ()
@property (nonatomic, strong) UIButton *lookBtn;
@property (nonatomic, strong) UIButton *doneBtn;

@property (nonatomic,strong) UIView *backgroundView;
@property (nonatomic,strong) UIImageView *backgroundImage;

@property (nonatomic,strong) UIImageView *leftImage;
@property (nonatomic,strong) UIImageView *rightImage;

@property (nonatomic,strong) UIImageView *centerImage;

//问题视图
@property (nonatomic,strong) MTQuestionAnswerView *questionView;
//问题文字框
@property (nonatomic,strong) XJTypeWriterTextView *questionTextView;
//选择框
@property (nonatomic,strong) UIView * choiceView;

@property (nonatomic,strong) NSString *isSuccess;
@property (nonatomic,strong) NSString *isUser;
@property (nonatomic,strong) NSString *isEnd;
@property (nonatomic,assign) NSInteger qCount;
@property (nonatomic,strong) NSString *isZan;

@property (nonatomic,strong) NSString *failStr;
@property(nonatomic ,strong) UIAlertController *alert;

@end

@implementation MTQuestionNpcAnswerVC
- (void) setNav {
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"jubao"] style:UIBarButtonItemStyleDone target:self action:@selector(rightClick)];
    self.navigationItem.rightBarButtonItem = rightBtn;
}
//举报
- (void)rightClick {
    [self.view endEditing:YES];
    if (!self.alert) {
        self.alert = [UIAlertController alertControllerWithTitle:@"请选择举报原因" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        [self.alert addAction:[UIAlertAction actionWithTitle:@"色情低俗" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            MTFeedBackVC *vc = GetViewControllerInStoryboard(@"Mine", @"MTFeedBackVC");
            [self.navigationController pushViewController:vc animated:YES];
        }]];
        [self.alert addAction:[UIAlertAction actionWithTitle:@"政治敏感" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //意见
            MTFeedBackVC *vc = GetViewControllerInStoryboard(@"Mine", @"MTFeedBackVC");
            [self.navigationController pushViewController:vc animated:YES];
        }]];
        [self.alert addAction:[UIAlertAction actionWithTitle:@"广告" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //意见
            MTFeedBackVC *vc = GetViewControllerInStoryboard(@"Mine", @"MTFeedBackVC");
            [self.navigationController pushViewController:vc animated:YES];
        }]];
        [self.alert addAction:[UIAlertAction actionWithTitle:@"令人恶心" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //意见
            MTFeedBackVC *vc = GetViewControllerInStoryboard(@"Mine", @"MTFeedBackVC");
            [self.navigationController pushViewController:vc animated:YES];
        }]];
        [self.alert addAction:[UIAlertAction actionWithTitle:@"违纪违法" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //意见
            MTFeedBackVC *vc = GetViewControllerInStoryboard(@"Mine", @"MTFeedBackVC");
            [self.navigationController pushViewController:vc animated:YES];
        }]];
        [self.alert addAction:[UIAlertAction actionWithTitle:@"其他" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //意见
            MTFeedBackVC *vc = GetViewControllerInStoryboard(@"Mine", @"MTFeedBackVC");
            [self.navigationController pushViewController:vc animated:YES];
        }]];
        [self.alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }]];
    }
    [self presentViewController:self.alert animated:true completion:nil];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNav];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"漂流卡";
    //初始化
    self.isSuccess = @"";
    self.isUser = @"";
    self.isEnd = @"";
    self.isZan = @"";
    self.failStr= @"";
    self.qCount = 1;
    //    self.dataArr = [NSMutableArray new];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.choiceView.hidden = YES;
        if (_dataArr.count > 0) {
            NSMutableDictionary *dic  = [_dataArr objectAtIndex:0];
            _questionTextView.content = [dic objectForKey:@"questionText"];
            [_questionTextView startTypewrite];
        }
    });
    _questionView.name.text = self.leftName;
    _questionView.rightName.text = self.rightName;
    
    [self.backgroundImage sd_setImageWithURL:[NSURL URLWithString:self.sceneUrl] ];

//placeholderImage:[UIImage imageNamed:@"背景图"]];
//    [_leftImage sd_setImageWithURL:[NSURL URLWithString:self.leftUrl] placeholderImage:[UIImage imageNamed:@"默认女"]];
//    [_rightImage sd_setImageWithURL:[NSURL URLWithString:self.rightUrl] placeholderImage:[UIImage imageNamed:@"默认男"]];
    
//    if ([self.sex isEqualToString:@"1"]) {
//        //男
//        [_centerImage sd_setImageWithURL:[NSURL URLWithString:self.leftUrl]]; placeholderImage:[UIImage imageNamed:@"默认天使男"]];
//    }else {
//        [_centerImage sd_setImageWithURL:[NSURL URLWithString:self.leftUrl] placeholderImage:[UIImage imageNamed:@"默认天使女"]];
//    }
    [_centerImage sd_setImageWithURL:[NSURL URLWithString:self.leftUrl]];
}

- (void)CreateNav {
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:YES];
}
- (void)initUI{
    
    [self.view addSubview:self.backgroundView];
//    [self.backgroundView addSubview:self.leftImage];
//    [self.backgroundView addSubview:self.rightImage];
    [self.backgroundView addSubview:self.centerImage];

//    [self.leftImage mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.bottom.mas_equalTo(0);
//        make.width.mas_equalTo(244);
//        make.height.mas_equalTo(456);
//    }];
//    [self.rightImage mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.bottom.mas_equalTo(0);
//        make.width.mas_equalTo(214);
//        make.height.mas_equalTo(436);
//    }];
//    self.leftImage.hidden = NO;
//    self.rightImage.hidden = YES;
    
    [self.centerImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.bottom.mas_equalTo(0);
        make.width.mas_equalTo(214);
        make.height.mas_equalTo(436);
    }];
    self.centerImage.contentMode = 2;
//    self.leftImage.contentMode = 2;
//    self.rightImage.contentMode = 2;
    

    [self.view addSubview:self.lookBtn];
    [self.view addSubview:self.doneBtn];
    self.doneBtn.hidden = YES;
    
    [self.backgroundView addSubview:self.questionView];
    [self.view addSubview:self.choiceView];
    self.choiceView.hidden = YES;
}
- (UIButton *)lookBtn{
    if (_lookBtn == nil) {
        CGRect rect = CGRectMake(12, kScreenHeight - 59 - 12 - BottomHeight, kScreenWidth - 24 , 59);
        _lookBtn = [[UIButton alloc] initWithFrame:rect text:@"赞TA的卡牌" textcolor:HEXCOLOR(0x333333) backgroundcolor:HEXCOLOR(0xFEF45C) fontSize:26 haveCorner:NO];
        _lookBtn.titleLabel.font = CLRudeCircleTextFont(18);
        _lookBtn.layer.cornerRadius = 10;
        _lookBtn.layer.masksToBounds = YES;
        _lookBtn.layer.borderWidth = 2;
        _lookBtn.layer.borderColor = KBlackColor.CGColor;
        [_lookBtn addTarget:self action:@selector(lookClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _lookBtn;
}
- (UIButton *)doneBtn{
    if (_doneBtn == nil) {
        CGRect rect = CGRectMake(12, kScreenHeight - 59 - 12 - BottomHeight, kScreenWidth - 24 , 59);
        _doneBtn = [[UIButton alloc] initWithFrame:rect text:@"领取" textcolor:HEXCOLOR(0x333333) backgroundcolor:HEXCOLOR(0xFEF45C) fontSize:26 haveCorner:NO];
        _doneBtn.titleLabel.font = CLRudeCircleTextFont(18);
        _doneBtn.layer.cornerRadius = 10;
        _doneBtn.layer.masksToBounds = YES;
        _doneBtn.layer.borderWidth = 2;
        _doneBtn.layer.borderColor = KBlackColor.CGColor;
        [_doneBtn addTarget:self action:@selector(doneClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _doneBtn;
}
- (UIView *)backgroundView{
    if (_backgroundView == nil) {
        CGRect rect = CGRectMake(12, NavHeight, kScreenWidth - 24  , kScreenHeight - 59 - 22 - BottomHeight - NavHeight);
        _backgroundView = [[UIView alloc] initWithFrame:rect];
        _backgroundView.layer.cornerRadius = 10;
        _backgroundView.layer.masksToBounds = YES;
        _backgroundView.backgroundColor = HEXCOLOR(0xEEEEEE);

        self.backgroundImage = [UIImageView new];
        [_backgroundView addSubview:self.backgroundImage];
        [self.backgroundImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.left.right.mas_equalTo(0);
        }];
//        self.backgroundImage.image = [UIImage imageNamed:@"背景图"];
    }
    return _backgroundView;
}
- (UIImageView *)leftImage{
    if (_leftImage == nil) {
        _leftImage = [UIImageView new];
        _leftImage.image = [UIImage imageNamed:@"默认天使女"];
        
    }
    return _leftImage;
}

- (UIImageView *)centerImage{
    if (_centerImage == nil) {
        _centerImage = [UIImageView new];
//        _centerImage.image = [UIImage imageNamed:@"默认天使女"];
    }
    return _centerImage;
}

- (UIImageView *)rightImage{
    if (_rightImage == nil) {
        _rightImage = [UIImageView new];
        _rightImage.image = [UIImage imageNamed:@"默认天使男"];
    }
    return _rightImage;
}
- (MTQuestionAnswerView *)questionView{
    if (_questionView == nil) {
        _questionView = [[MTQuestionAnswerView alloc] initWithFrame:CGRectMake(0, self.backgroundView.height - 150, kScreenWidth - 24,150 )];
        _questionTextView = [[XJTypeWriterTextView alloc] initWithFrame:CGRectMake(22, 30, kScreenWidth-22*2-24, 100)];
        _questionTextView.backgroundColor = [UIColor clearColor];
        _questionTextView.font = CLRudeCircleTextFont(18);
        _questionTextView.hasSound = NO;
        _questionTextView.typewriteEffectColor = KWhiteColor;
        _questionTextView.textColor = KWhiteColor;
        _questionTextView.textAlignment = NSTextAlignmentCenter;
        _questionTextView.typewriteTimeInterval = 0.1;
        _questionTextView.editable = NO;
        
        _questionTextView.typewriteEffectBlock = ^(){
            if ([self.isUser isEqualToString:@"1"]) {
                self.isUser = @"";
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self.rightImage.hidden = YES;
                    self.leftImage.hidden = NO;
                    _questionView.rightName.hidden = YES;
                    _questionView.name.hidden = NO;
                    
                    
                    if ([self.isEnd isEqualToString:@"1"]) {
                        if ([self.isSuccess isEqualToString:@"1"]) {
                            if (self.storyVersion.length > 0) {
                                [self saveUsersStoryRecord:@"1"];
                            }
                            //成功
                            self.doneBtn.hidden = NO;
//                            self.lookBtn.width = kScreenWidth - 24 - kFit(90) - 10;
                            [self.doneBtn setTitle:@"领取" forState:UIControlStateNormal];
                            _questionView.name.text = @"GET!";
                            _questionView.name.textColor = KMainColor;
                            _questionTextView.content = @"攻略成功 获得10车票";
                            [_questionTextView startTypewrite];
                        }else {
                            if (self.storyVersion.length > 0) {
                                [self saveUsersStoryRecord:@"0"];
                            }
                            NSDictionary *dic = [self.dataArr objectAtIndex:self.qCount - 2];
//                            NSString *fail = @"";
//                            if ([[dic objectForKey:@"remarks"] isEqualToString:@""]) {
//                                fail = @"没有通过我创建的卡牌";
//                            }else {
//                                fail = [dic objectForKey:@"remarks"];
//                            }
                            //失败
                            self.doneBtn.hidden = NO;
//                            self.lookBtn.width = kScreenWidth - 24 - kFit(90) - 10;
                            _questionView.name.text = @"LOSE";
                            _questionView.name.textColor = KMainColor;
                            _questionTextView.content = self.failStr;
                            [_questionTextView startTypewrite];
                            
                            [self.doneBtn setTitle:@"GG" forState:UIControlStateNormal];
                        }
                    }else {
                        NSDictionary *dic = [self.dataArr objectAtIndex:self.qCount - 1];
                        _questionTextView.content = [dic objectForKey:@"questionText"];
                        [_questionTextView startTypewrite];
                    }
                });
            }else {
                self.rightImage.hidden = YES;
                self.leftImage.hidden = NO;
                _questionView.rightName.hidden = YES;
                _questionView.name.hidden = NO;
                
                if ([self.isEnd isEqualToString:@"1"]) {
                    return ;
                }
                [self reloadAnswer];
                self.choiceView.hidden = NO;
            }
            
        };
        [_questionView addSubview:_questionTextView];
        
    }
    
    return _questionView;
}
- (UIView *)choiceView {
    if (_choiceView == nil) {
        _choiceView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight/2.0 - 130  , kScreenWidth, 81*3)];
        _choiceView.backgroundColor = [UIColor clearColor];
        for (int i = 0; i < 3; i++) {
            CLChocieAnswerButton * choiceButton = [[CLChocieAnswerButton alloc] init];
            choiceButton.frame = CGRectMake(25, 14 + (65+10)*i, kScreenWidth - 50, 65);
            [_choiceView addSubview:choiceButton];
            choiceButton.layer.borderWidth = 2;
            choiceButton.layer.cornerRadius = 4;
            choiceButton.layer.masksToBounds = YES;
            
            choiceButton.layer.borderColor = KBlackColor.CGColor;
            choiceButton.tag = kChoiceButtonTag + i;
            [choiceButton addTarget:self action:@selector(clickChoiceButton:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    return _choiceView;
}
- (void)reloadAnswer {
    CLChocieAnswerButton *but = [_choiceView viewWithTag:kChoiceButtonTag + 1];
    if (but) {
        but.hidden = NO;
    }
    
    NSDictionary *dic = [self.dataArr objectAtIndex:self.qCount - 1];
    NSArray *infoArr = [dic objectForKey:@"answerList"];
    
    for (int i = 0; i < infoArr.count; i++) {
        CLChocieAnswerButton * button = [_choiceView viewWithTag:kChoiceButtonTag + i];
        NSDictionary *info = [infoArr objectAtIndex:i];
        if (i == 0) {
            [button setTextToButton:[info objectForKey:@"answerText"]];
        } else if (i == 1) {
            [button setTextToButton:[info objectForKey:@"answerText"]];
        }else if (i == 2) {
            [button setTextToButton:[info objectForKey:@"answerText"]];
        }
    }
}
- (void)clickChoiceButton:(CLChocieAnswerButton *) sender {
    if (self.dataArr.count == 0) {
        return;
    }
    NSDictionary *dic = [self.dataArr objectAtIndex:self.qCount - 1];
    NSArray *infoArr = [dic objectForKey:@"answerList"];
    self.rightImage.hidden = NO;
    self.leftImage.hidden = YES;
    _questionView.rightName.hidden = NO;
    _questionView.name.hidden = YES;
    switch (sender.tag - kChoiceButtonTag) {
        case 0:
        {
            if (infoArr.count < 1) {
                return;
            }
            NSDictionary *info = [infoArr objectAtIndex:0];
            if (self.qCount == self.dataArr.count) {
                if ([[NSString stringWithFormat:@"%@",[info objectForKey:@"resultType"]]isEqualToString:@"2"]) {
                    self.isSuccess = @"1";
                }else {
                    self.isSuccess = @"0";
                }
                self.isEnd = @"1";
            }else {
                
                if ([[NSString stringWithFormat:@"%@",[info objectForKey:@"resultType"]]isEqualToString:@"0"]) {
                    
                }else {
                    self.isSuccess = @"0";
                    self.isEnd = @"1";
                }
            }
            self.qCount ++;
            self.choiceView.hidden = YES;
            self.isUser = @"1";
            _questionTextView.content = [info objectForKey:@"answerText"];
            self.failStr = [info objectForKey:@"remark"];

            [_questionTextView startTypewrite];
        }
            break;
        case 1:
        {
            if (infoArr.count < 2) {
                return;
            }
            NSDictionary *info = [infoArr objectAtIndex:1];
            if (self.qCount == self.dataArr.count) {
                if ([[NSString stringWithFormat:@"%@",[info objectForKey:@"resultType"]]isEqualToString:@"2"]) {
                    self.isSuccess = @"1";
                }else {
                    self.isSuccess = @"0";
                }
                self.isEnd = @"1";
            }else {
                
                if ([[NSString stringWithFormat:@"%@",[info objectForKey:@"resultType"]]isEqualToString:@"0"]) {
                    
                }else {
                    self.isSuccess = @"0";
                    self.isEnd = @"1";
                }
            }
            self.qCount ++;
            self.choiceView.hidden = YES;
            self.isUser = @"1";
            _questionTextView.content = [info objectForKey:@"answerText"];
            self.failStr = [info objectForKey:@"remark"];

            [_questionTextView startTypewrite];
        }
            break;
        case 2:
        {
            if (infoArr.count < 3) {
                return;
            }
            NSDictionary *info = [infoArr objectAtIndex:2];
            if (self.qCount == self.dataArr.count) {
                if ([[NSString stringWithFormat:@"%@",[info objectForKey:@"resultType"]]isEqualToString:@"2"]) {
                    self.isSuccess = @"1";
                }else {
                    self.isSuccess = @"0";
                }
                self.isEnd = @"1";
            }else {
                
                if ([[NSString stringWithFormat:@"%@",[info objectForKey:@"resultType"]]isEqualToString:@"0"]) {
                    
                }else {
                    self.isSuccess = @"0";
                    self.isEnd = @"1";
                }
            }
            self.qCount ++;
            self.choiceView.hidden = YES;
            self.isUser = @"1";
            _questionTextView.content = [info objectForKey:@"answerText"];
            self.failStr = [info objectForKey:@"remark"];

            [_questionTextView startTypewrite];
        }
            break;
        default:
            break;
    }
}
//点赞
- (void)lookClick {
    if ([self.isZan isEqualToString:@"1"]) {
        [self.view maketishiToast:@"已点赞"];
    }else {
        if (self.storyVersion.length > 0) {
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            AccountService *acc = [AccountService getObject];
            acc.httpRequestResultBlock = ^(id data,int code){
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if (code == 1) {
                    [self.view maketishiToast:@"点赞成功"];
                    self.isZan = @"1";
                }else {
                    [self.view maketishiToast:data];
                }
            };
            [acc addPrase:self.storyId storyVersion:self.storyVersion];
        }else {
            self.isZan = @"1";
            [self.view maketishiToast:@"点赞成功"];
        }
    }
}

- (void)doneClick {
    if ([self.isSuccess isEqualToString:@"1"]) {
        //领取
        AccountService *acc = [AccountService getObject];
        acc.httpRequestResultBlock = ^(id data,int code){
            if (code == 1) {
                [[UIApplication sharedApplication].keyWindow maketicket2Toast:@"10"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
                if (self.hasAnswer) {
                    self.hasAnswer(@"1");
                }
            }else {
                [self.view maketishiToast:data];
            }
        };
        [acc usersAddTicket];
    }else {
        if (self.hasAnswer) {
            self.hasAnswer(@"1");
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//添加答题记录
- (void)saveUsersStoryRecord:(NSString *) isTrue{
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        if (code == 1) {
            if (self.hasAnswer) {
                self.hasAnswer(@"1");
            }
            if ([isTrue isEqualToString:@"1"]) {
                // 答题成功的
//                [self success];
            }else {
                
            }
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc saveUsersStoryRecord:self.storyId storyVersion:self.storyVersion isTrue:isTrue createUsersId:self.createUsersId createType:@"0"];
}

- (void)success {
    NSDictionary *dict = @{@"records":@"1",
                           @"send_username":KUSER.nickName,
                           @"username":KUSER.nickName,
                           @"recever_username":self.leftName,
                           @"headImageUrl":KUSER.portraitMap,
                           @"send_details":@""
                           };
    EMTextMessageBody *msgB = [[EMTextMessageBody alloc] initWithText:@"通过考验"];
    NSString *from = [[EMClient sharedClient] currentUsername];
    NSString *to = [NSString stringWithFormat:@"met_%@",self.createUsersId];
    //    self.conversation.conversationId;
    EMMessage *message = [[EMMessage alloc] initWithConversationID:to from:from to:to body:msgB ext:dict];
    message.chatType = EMChatTypeChat; // 消息类型
    message.ext = dict;
    __weak typeof(self) weakSelf = self;
    // 发送消息 （调用 EaseMessageViewController 中的方法）
    [[EMClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
    } completion:^(EMMessage *message, EMError *error) {
        if (!error) {
            //            [weakSelf addMessageToDataSource:message progress:nil];
            //            [weakSelf.tableView reloadData];
        }
    }];
}
@end
